<template>
  <tm-app color="#F1F4FA">
    <view class="chat-content">
      <z-paging ref="paging" :auto="false" v-model="dataList" use-chat-record-mode use-virtual-list
        cell-height-mode="dynamic" safe-area-inset-bottom auto-hide-keyboard-when-chat
        :auto-adjust-position-when-chat="false" bottom-bg-color="#f8f8f8" @query="queryList">
        <template #top>
          <Navbar hideHome :fontSize="40" title="灵犀助手" color="#F1F4FA" :shadow="0">
            <template v-slot:right>
              <view class="info mr-40">
                <tm-text class="mr-8" :font-size="20" color="#34345D" label="当前档案"></tm-text>
                <view class="tag">{{ userInfo?.name || '' }}</view>
              </view>
            </template>
            <!-- <template v-slot:left>
              <image class="history_image" mode="widthFix" @click="drawerShow = !drawerShow" :src="history_image">
              </image>
            </template> -->
          </Navbar>
        </template>
        <template #cell="{ item, index }">
          <view :style="{
            paddingBottom: '40rpx',
            paddingLeft: '40rpx',
            paddingRight: '40rpx',
            transform: 'scaleY(-1)'
          }">
            <PersonalInfo @reportClick="handleReportClick" :item="item" v-if="item.type === 'user'" />
            <ChatItem @reportClick="handleReportClick" v-else :item="item" :finish="item.finish" />
          </view>
        </template>
        <template #bottom>
          <view class="chat-view">
            <tm-input v-model="askText" :height="76" :padding="[0, 20]" :round="10" placeholder="有问题尽管问我吧~"
              class="input"></tm-input>
            <image v-if="!isAnswering" @click="doSend" class="send-image" :src="send_image" />
            <image v-else class="loading_image" :src="loading_image" />
          </view>
          <Tabbar />
        </template>
      </z-paging>
    </view>
    <gao-ChatSSEClient
        :heartbeat-timeout="600000"
        :timeout="6000000"
        :max-retry-count="5"
        ref="chatSSEClientRef" @onError="onChatMessageError" @onMessage="onChatMessage"
      @onFinish="onChatMessageFinish" />
    <tm-drawer class="drawer" :round="0" hideHeader :width="434" placement="left" v-model:show="drawerShow">
      <view class="drawer-content">
        <view class="title">历史对话记录</view>
        <view v-for="i in 3" class="card">
          <view class="card-title">今天</view>
          <view class="card-content">
            <tm-text class="mt-24" _class="text-overflow-1" :font-size="32" color="#444444"
              label="根据您的四柱分析，您：你刚柔并济，外表坚强刚硬，但怀有仁慈之心。你具有坚韧不拔的品质，富有勇气和冲劲，为人正直，责任感强，是值得信赖的对象。你为人处世简单直接，喜静不喜动，不擅长理解分析繁复的变化，也不喜欢频繁的变动。你有深远的智慧，一般是少言寡语，是头脑聪敏之人。"></tm-text>
          </view>
        </view>
      </view>
    </tm-drawer>

    <userModal ref="userModalRef" />

    <UserReportModal ref="userReportModalRef" />
  </tm-app>
</template>

<script lang="ts" setup>
  import { ref, computed, nextTick } from 'vue';
  import history_image from '/static/assets/images/matters/history.png';
  import send_image from '/static/assets/images/matters/send.png';
  import loading_image from '/static/assets/images/matters/loading.gif';
  import Navbar from '@/components/navbar/index.vue';
  import ChatItem from './components/ChatItem/ChatItem.vue';
  import PersonalInfo from './components/PersonalInfo/PersonalInfoCard.vue'
  import { useUserStore } from "@/stores/user";
  import { useAiChat } from "@/stores/aiChat"
  import { aiChat } from "@/services/apis/index";
  import Tabbar from '@/components/tabbar/index.vue'
  import userModal from '@/components/userModal/index.vue'
  import UserReportModal from './components/UserReportModal/UserReportModal.vue'
  import { isEmpty } from 'lodash';
  import { onShow } from "@dcloudio/uni-app"

  const drawerShow = ref(false)
  const paging = ref(null);
  const dataList = ref([]);
  const askText = ref('');
  const isAnswering = ref(false);
  const aiChatStore = useAiChat();
  const chatSSEClientRef = ref(null);
  const userModalRef = ref(null);
  const userReportModalRef = ref(null);

  const INIT_MESSAGE = '我的四柱分析'
  const THINKING_MESSAGE = '思考中...'
  const ERORR_MESSAGE = '服务器错误，请稍后再试...'

  const userStore = useUserStore();

  const userInfo = computed(() => {
    return userStore?.userInfo;
  })

  const queryList = async (pageNo, pageSize) => {
    if (isEmpty(userInfo.value)) return

    paging.value.complete([{
      type: 'user',
      text: THINKING_MESSAGE
    },]);
    sendSSE(INIT_MESSAGE)
  }

  const doSend = async () => {
    if (isAnswering.value || !askText.value) {
      // 如果在回答中，不允许发送新的消息，避免数据错乱
      return;
    }
    send(askText.value)
    received(THINKING_MESSAGE)
    const prompt = askText.value
    askText.value = ''
    sendSSE(prompt)
  }

  const sendSSE = async (msg) => {
    isAnswering.value = true;
    chatSSEClientRef.value.startChat({
      url: `${aiChat.stream}?prompt=${msg}`,
      // 请求头
      headers: {
        Authorization: `Bearer ${userStore.token}`,
        'Access-Control-Allow-Origin': '*'
      },
      method: 'get',
    })
  }

  const onChatMessage = (msg) => {
    try {
      const data = JSON.parse(msg?.data);
      received(data?.choices?.[0]?.delta?.content || '', false)
    } catch (error) {

    }
  }

  const onChatMessageFinish = () => {
    dataList.value[0].finish = true;
    isAnswering.value = false;
  }

  const onChatMessageError = () => {
    received(ERORR_MESSAGE, false)
  }

  const send = (msg) => {
    paging.value.addChatRecordData({
      text: msg,
      me: true
    });
  }

  const received = (msg, isAdd = true) => {
    if (isAdd) {
      paging.value.addChatRecordData({
        text: msg,
        me: false
      });
    } else {
      if (!dataList.value.length) return

      // 清除首次加载时的'思考中...'提示
      if (dataList.value[0].text === THINKING_MESSAGE) {
        dataList.value[0].text = '';
      }
      dataList.value[0].text += msg;
    }
  }

  const handleReportClick = () => {
    userReportModalRef.value?.handleUserReport()
  }

  onShow(async () => {
    await nextTick()
    userModalRef.value?.handleUserVaild()
    if (isEmpty(userInfo.value) || dataList.value.length) return
    // 重新初始化
    paging.value?.reload()
  })
</script>

<style lang="less" scoped>
  .app {}

  .history_image {
    width: 42rpx;
    margin-left: 46rpx;
  }

  .info {
    display: flex;
    align-items: center;

    .tag {
      font-size: 24rpx;
      color: #34345D;
      background-color: #fff;
      padding: 0 4rpx;
      border-radius: 4rpx;
    }
  }

  .chat-view {
    height: 134rpx;
    width: 750rpx;
    display: flex;
    padding: 30rpx;
    background-color: #fff;
    justify-content: space-between;
    align-items: center;

    .input {
      flex: 1;
    }

    .send-image {
      width: 56rpx;
      height: 48rpx;
      margin-left: 20rpx;
    }

    .loading_image {
      width: 48rpx;
      height: 48rpx;
      margin-left: 20rpx;
    }
  }

  .drawer-content {
    padding: calc(34rpx + var(--status-bar-height)) 40rpx;

    .title {
      font-size: 36rpx;
      color: #444444;
    }

    .card {
      margin-top: 60rpx;

      .card-title {
        font-size: 32rpx;
        color: #999999;
      }
    }
  }
</style>
